package com.bsj.power.pls.task;

import com.bsj.power.common.constant.NumericalConstants;
import com.bsj.power.common.util.DateUtils;
import com.bsj.power.pls.cache.PanelCache;
import com.bsj.power.pls.netty.CTInstructUtils;
import com.bsj.power.pls.netty.CachedChannelMap;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.iot.mqtt.core.server.MqttServer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author LiJiaXin
 * @version 1.0.0
 * @description ScheduledExecutorServiceExample
 * @time 2024/9/25 9:58
 */
@Slf4j
@Component
public class GetACDataScheduledTask {

    @Autowired
    private MqttServer mqttServer;

    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    /**
     * 每十秒请求一次绑卡机状态信息
     *
     * @return void
     * @author ljx
     * @time 2024/9/25 10:08
     */
    @PostConstruct
    public void startScheduledTask() {
        Runnable task = () -> {
            //TODO 实现查询绑卡机状态
            Map<String, String> bindRelationMap = PanelCache.BIND_RELATION_MAP;
            if (!CollectionUtils.isEmpty(bindRelationMap)) {
                List<String> deviceIds = bindRelationMap.values().stream().collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(deviceIds)) {
                    deviceIds.forEach(deviceId -> {
                        String clientId = CachedChannelMap.getClientId(deviceId);
                        if (StringUtils.isBlank(clientId)) {
                            log.warn("绑卡机设备离线：{}", deviceId);
                        } else {
                            mqttServer.publish(clientId, CTInstructUtils.getTopicSend(deviceId)
                                    , CTInstructUtils.assembleDevStateQueryCmd(deviceId, NumericalConstants.ZERO));
                            log.info("定时任务执行请求设备状态信息指令发送成功：{}", DateUtils.dateToStr(new Date(System.currentTimeMillis())));
                        }
                    });
                }
            }
        };
        //初始延迟0秒，之后每5秒执行一次
        scheduler.scheduleAtFixedRate(task, 0, 10, TimeUnit.SECONDS);
    }

}
